#include<algorithm>
#include<cstdio>
#include<vector>
#include<unordered_map>
#include<iostream>
using namespace std;
const int maxn=1e4;
#define mp(x,y) make_pair((x),(y))
vector<pair<string,int>> A;
vector<pair<string,int>> B;
vector<pair<string,int>> T;
unordered_map<string,pair<int,int>>testee;
unordered_map<string,unordered_map<string,int>>card;

bool cmp1(pair<string,int> a,pair<string,int> b){
    if(a.second!=b.second){return a.second>b.second;}
    return a.first<b.first;
}

int main(){
    //freopen("in.txt","r",stdin);

    int N,M;
    scanf("%d %d",&N,&M);
    string id;int score;
    for(int i=0;i<N;i++){
        cin>>id;scanf("%d",&score);
        if(id[0]=='A'){A.push_back(mp(id,score));}
        else if(id[0]=='B'){B.push_back(mp(id,score));}
        else if(id[0]=='T'){T.push_back(mp(id,score));}
        string site=id.substr(1,3);
        testee[site].first++;
        testee[site].second+=score;
        string date=id.substr(4,6);
        card[date][site]++;
    }
    int queid;string pas;
    for(int i=0;i<M;i++){
        scanf("%d",&queid);cin>>pas;
        printf("Case %d: %d %s\n",i+1,queid,pas.c_str());
        if(queid==1){
            if(pas=="A"){
                if(A.size()==0){printf("NA\n");continue;}
                sort(A.begin(),A.end(),cmp1);
                for(int i=0;i<A.size();i++){
                    printf("%s %d\n",A[i].first.c_str(),A[i].second);
                }
            }
            else if(pas=="B"){
                if(B.size()==0){printf("NA\n");continue;}
                sort(B.begin(),B.end(),cmp1);
                for(int i=0;i<B.size();i++){
                    printf("%s %d\n",B[i].first.c_str(),B[i].second);
                }
            }
            else if(pas=="T"){
                if(T.size()==0){printf("NA\n");continue;}
                sort(T.begin(),T.end(),cmp1);
                for(int i=0;i<T.size();i++){
                    printf("%s %d\n",T[i].first.c_str(),T[i].second);
                }
            }
        }
        else if(queid==2){
            if(testee.find(pas)==testee.end()){printf("NA\n");continue;}
            printf("%d %d\n",testee[pas].first,testee[pas].second);
        }
        else if(queid==3){
            if(card.find(pas)==card.end()){printf("NA\n");continue;}
            vector<pair<string,int>>ans;
            for(auto it=card[pas].begin();it!=card[pas].end();it++){
                ans.push_back(*it);
            }
            sort(ans.begin(),ans.end(),cmp1);
            for(int i=0;i<ans.size();i++){
                printf("%s %d\n",ans[i].first.c_str(),ans[i].second);
            }
        }
    }
}
